package com.jingli.pile.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingli.pile.configuration.PushProperties;
import com.jingli.pile.domain.CommonDataResult;
import com.jingli.pile.domain.TokenResult;
import com.jingli.pile.entity.PlatformInfo;
import com.jingli.pile.request.TokenQueryRequest;
import com.jingli.pile.service.PlatformInfoService;
import com.jingli.pile.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping()
public class ApiController {
    private Logger logger = LoggerFactory.getLogger(ApiController.class);
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private JwtGenerator jwtGenerator;
    @Autowired
    private PlatformInfoService platformInfoService;
    @Autowired
    private PlatformGenerator platformGenerator;
    @Autowired
    private ThirdParty thirdParty;
    @Autowired
    PushProperties pushProperties;

    @RequestMapping("/generate_platform")
    @ResponseBody
    public void generatePlatform(){
        PlatformInfo generate = platformGenerator.generate();
        platformInfoService.save(generate);
    }

    @RequestMapping("/queryProdToken/{platformId}")
    @ResponseBody
    public String queryProdToken(@PathVariable("platformId") String platformId){
        String token = thirdParty.getToken(platformId);
        return token;
    }

    @RequestMapping("/evcs/v1/query_token")
    @ResponseBody
    public CommonDataResult queryToken(@RequestBody TokenQueryRequest queryRequest)throws Exception{
        logger.info("收到请求token参数:{}",JSONObject.toJSONString(queryRequest));
        QueryWrapper<PlatformInfo> platformInfoQueryWrapper = new QueryWrapper<>();
        platformInfoQueryWrapper.eq("platform_id",queryRequest.getPlatformID());
        platformInfoQueryWrapper.eq("env",pushProperties.getEnv());
        PlatformInfo platformInfo = platformInfoService.getOne(platformInfoQueryWrapper);
        if (null==platformInfo){
            return CommonDataResult.failure(1001,"根据消息体中的组织机构代码，获取不到商户","","");
        }
        String decrypted = MessageEncryption.decrypt(queryRequest.getData(), pushProperties.getDataSecret(), pushProperties.getDataSecretIV());
        logger.info("解密后的平台信息:{}",decrypted);
        JSONObject jsonObject = JSONObject.parseObject(decrypted);
        String platformId = jsonObject.getString("PlatformID");
        String platformSecret = jsonObject.getString("PlatformSecret");
        authenticate(platformId,platformSecret);
        TokenResult tokenResult = jwtGenerator.generateToken(platformInfo);
        logger.info("返回的token:{}",tokenResult.getAccessToken());
        String signParams = PileSignUtils.signParams(JSONObject.toJSONString(tokenResult), pushProperties.getDataSecret(), pushProperties.getDataSecretIV());
        String sign = HmacMd5Signature.hmacMd5(signParams,pushProperties.getSignSecret());
        return CommonDataResult.success(signParams,sign);
    }

    private void authenticate(String username, String password) throws Exception {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (BadCredentialsException e) {
            throw new Exception("平台信息错误", e);
        }
    }
}
